public Class CommonMethod
{
    //加载城市资源列表
    public List<CityResourceAllcation__c> LoadCityList(string filter,string activityId)
    {
        string sql='select Resource_Allocation__r.Product_Name__r.Name,PackSize__c ,Subregion__c,OutletNumber__c,'+
                         ' Region__c,Area__c,Type__c,KAName__c,CityName__c,ResourceNumber__c from CityResourceAllcation__c '+
                         'where Activity_Information__c=\''+activityId+'\'';
                        
         if(filter!=NULL)
             sql+=filter;
             
         sql+=' order by Resource_Allocation__r.Product_Name__r.Name';
         //throw new CustomException(sql);
         return Database.query(sql);
    }
    //条件过滤，KA名称，活动ID
    public List<Resource_Allocation_Detail__c> LoadOutletList(String filter,string activityId)
     {
         List<Resource_Allocation_Detail__c> resourceDetailList=new List<Resource_Allocation_Detail__c>();
            //加载分配列表
           String sql='select Convert_To_Quantity_Number__c,ReourceOutletType__c,Resource_Quantity_Number__c,Participator_Detail_Outlet__r.Outlet_Type__c,'+
                             'Participator_Detail_Outlet__r.City__c,Participator_Detail_Outlet__r.Area__c,Participator_Detail_Outlet__r.SubRegion__c,'+
                             'id,outletID__c,Resource_Allocation__r.Product_Name__r.Name,Resource_Number__c,HasUsedResourceNumber__c, '+
                             ' Participator_Detail_Outlet__r.Outlet_Name__r.Name,Resource_Allocation__r.Resource_Type__c,Participator_Detail_Outlet__r.Outlet_Name__r.With_NC_or_not__c  '+
                             ' from Resource_Allocation_Detail__c'+
                             ' where ActivityId__c=\''+activityId+'\'';
                                               
                if(filter!=NULL || filter!='')
                      sql+=filter;
                      
              sql+=' order by Resource_Allocation__r.Product_Name__r.Name,Participator_Detail_Outlet__r.Outlet_Type__c,Participator_Detail_Outlet__r.Outlet_Name__r.With_NC_or_not__c asc';
          //   sql+=' order by Participator_Detail_Outlet__r.Outlet_Type__c asc';
            resourceDetailList=Database.query(sql);
           
            return resourceDetailList;
     }
     //按分配资源获取动态列
     public List<String> GetDynamicETColumnList(List<Resource_Allocation_Detail__c> resourceDetailList)
     {  
          List<String> ETColumnList=new List<String>();//列
          Set<String> columnList=new Set<String>();
            for(Resource_Allocation_Detail__c rad:resourceDetailList)
            {
                  if(!columnList.contains(rad.Resource_Allocation__r.Product_Name__r.Name))
                {
                    ETColumnList.add(rad.Resource_Allocation__r.Product_Name__r.Name);
                     columnList.add(rad.Resource_Allocation__r.Product_Name__r.Name);
                }  
           }
                return  ETColumnList;
     }
      //获取动态列,方法重载
     public List<String> GetDynamicETColumnList(List<AggregateResult> groupResourceList)
     {  
          List<String> ETColumnList=new List<String>();//列
          Set<String> columnList=new Set<String>();
          
            for(AggregateResult rad:groupResourceList)
            {
                  if(!columnList.contains((String)rad.get('ResourceName')))
                 {
                     ETColumnList.add((String)rad.get('ResourceName'));
                     columnList.add((String)rad.get('ResourceName'));
                  }  
           }
                return  ETColumnList;
     }
     //按城市获取动态列，方法重载
     public List<String> GetDynamicETColumnList(List<CityResourceAllcation__c> cityResourceList)
     {
         List<String> ETColumnList=new List<String>();//列
          Set<String> columnList=new Set<String>();
          
            for(CityResourceAllcation__c rad:cityResourceList)
            {
                  if(!columnList.contains(rad.Resource_Allocation__r.Product_Name__r.Name))
                 {
                     ETColumnList.add(rad.Resource_Allocation__r.Product_Name__r.Name);
                     columnList.add(rad.Resource_Allocation__r.Product_Name__r.Name);
                  }  
           }
                return  ETColumnList;
     }
     //获取KA的分配信息，OT页面使用
     public List<DynamicColumnEntry>GetDynamicEntryList(List<AggregateResult> kaResourceList)
     {
          Map<String,DynamicColumnEntry> mapList=new map<String,DynamicColumnEntry>();//资源列表
          List<DynamicColumnEntry> DynamicColumnEntryList=new List<DynamicColumnEntry>();
           for(AggregateResult rad:kaResourceList)
           {
                if(!mapList.containsKey((String)rad.get('KAName__c')))
                {
                    DynamicColumnEntry entry=new DynamicColumnEntry();
                     entry.OutletName=(String)rad.get('KAName__c');
                     entry.Resource1=Integer.valueOf(rad.get('Total'));
                     
                     entry.Resource2=-1;
                     entry.Resource3=-1;
                     entry.Resource4=-1;
                     entry.Resource5=-1;
                     mapList.put((String)rad.get('KAName__c'),entry);
                }
                else
                {
                       DynamicColumnEntry entry=mapList.get((String)rad.get('KAName__c'));
                       if(entry.Resource2==-1)
                           entry.Resource2=Integer.valueOf(rad.get('Total'));
                      else  if(entry.Resource3==-1)
                           entry.Resource3=Integer.valueOf(rad.get('Total'));
                      else  if(entry.Resource4==-1)
                           entry.Resource4=Integer.valueOf(rad.get('Total'));
                      else if(entry.Resource5==-1)
                           entry.Resource5=Integer.valueOf(rad.get('Total'));
                          
                     mapList.put((String)rad.get('KAName__c'),entry);
                }
           }
           DynamicColumnEntryList=mapList.values();
           return DynamicColumnEntryList;
     }
     
     //获取城市列表实体
       public List<DynamicColumnEntry>GetDynamicEntryList(List<CityResourceAllcation__c> cityResourceList)
       {
           Map<String,DynamicColumnEntry> mapList=new map<String,DynamicColumnEntry>();//资源列表
          List<DynamicColumnEntry> DynamicColumnEntryList=new List<DynamicColumnEntry>();
           for(CityResourceAllcation__c rad:cityResourceList)
           {
                if(!mapList.containsKey(rad.CityName__c))
                {
                    DynamicColumnEntry entry=new DynamicColumnEntry();
                    entry.Region=rad.Region__c;
                    entry.Subregion=rad.Subregion__c;
                    entry.Area=rad.Area__c;
                     entry.City=rad.CityName__c;
                     entry.idString=rad.id;
                     entry.OutletName=rad.CityName__c;
                     entry.OutletNumber=Integer.valueOf(rad.OutletNumber__c);
                     entry.Resource1=Integer.valueOf(rad.ResourceNumber__c);
                     entry.resourceId1=rad.Resource_Allocation__c;
                     entry.ResourcePackSize1=Integer.valueOf(rad.PackSize__c);
                     
                     entry.Resource2=-1;
                     entry.Resource3=-1;
                     entry.Resource4=-1;
                     entry.Resource5=-1;
                     mapList.put(rad.CityName__c,entry);
                }
                else
                {
                       DynamicColumnEntry entry=mapList.get(rad.CityName__c);
                       if(entry.Resource2==-1)
                       {
                           entry.Resource2=Integer.valueOf(rad.ResourceNumber__c);
                           entry.resourceId2=rad.Resource_Allocation__c;
                           entry.ResourcePackSize2=Integer.valueOf(rad.PackSize__c);
                       }
                      else  if(entry.Resource3==-1)
                      {
                           entry.Resource3=Integer.valueOf(rad.ResourceNumber__c);
                           entry.resourceId3=rad.Resource_Allocation__c;
                           entry.ResourcePackSize3=Integer.valueOf(rad.PackSize__c);
                      }
                      else  if(entry.Resource4==-1)
                      {
                           entry.Resource4=Integer.valueOf(rad.ResourceNumber__c);
                           entry.resourceId4=rad.Resource_Allocation__c;
                           entry.ResourcePackSize4=Integer.valueOf(rad.PackSize__c);
                      }
                      else if(entry.Resource5==-1)
                      {
                           entry.Resource5=Integer.valueOf(rad.ResourceNumber__c);
                           entry.resourceId5=rad.Resource_Allocation__c;
                           entry.ResourcePackSize5=Integer.valueOf(rad.PackSize__c);
                      }
                       mapList.put(rad.CityName__c,entry);
                }
           }
           DynamicColumnEntryList=mapList.values();
           //System.assert(false,DynamicColumnEntryList);
           return DynamicColumnEntryList;
       }
     //获取门店列表实体
     public  List<DynamicColumnEntry> GetDynamicEntryList(List<Resource_Allocation_Detail__c> resourceDetailList)
     {
          Map<String,DynamicColumnEntry> mapList=new map<String,DynamicColumnEntry>();//资源列表
          List<DynamicColumnEntry> DynamicColumnEntryList=new List<DynamicColumnEntry>();
          
            for(Resource_Allocation_Detail__c rad:resourceDetailList)
            {
                 Decimal num=rad.Resource_Quantity_Number__c;//按个显示资源数
                
                 if(!mapList.containsKey(rad.outletID__c))
                 {
                     DynamicColumnEntry entry=new DynamicColumnEntry();
                     entry.IsCheck=false;
                     entry.OutletStatus=rad.Participator_Detail_Outlet__r.Outlet_Type__c;
                     entry.Subregion=rad.Participator_Detail_Outlet__r.SubRegion__c;
                     entry.Area=rad.Participator_Detail_Outlet__r.Area__c;
                     entry.City=rad.Participator_Detail_Outlet__r.City__c;
                     entry.idString=rad.id;
                     entry.OutletName=rad.Participator_Detail_Outlet__r.Outlet_Name__r.Name;
                     entry.WithoutNCOrNot=rad.Participator_Detail_Outlet__r.Outlet_Name__r.With_NC_or_not__c;
                     entry.Resource1=num.intValue();
                     entry.resourceId1=rad.Resource_Allocation__c;
                     entry.ParticipatorId=rad.Participator_Detail_Outlet__c;
                     
                     entry.Resource2=-1;
                     entry.Resource3=-1;
                     entry.Resource4=-1;
                     entry.Resource5=-1;
                     mapList.put(rad.outletID__c,entry);
                 }
               else
               {
                   DynamicColumnEntry entry=mapList.get(rad.outletID__c);
                   if(entry.Resource2==-1)
                   {
                       entry.Resource2=num.intValue();
                       entry.resourceId2=rad.Resource_Allocation__c;
                   }
                  else  if(entry.Resource3==-1)
                  {
                       entry.Resource3=num.intValue();
                       entry.resourceId3=rad.Resource_Allocation__c;
                  }
                  else  if(entry.Resource4==-1)
                  {
                       entry.Resource4=num.intValue();
                       entry.resourceId4=rad.Resource_Allocation__c;
                  }
                  else if(entry.Resource5==-1)
                  {
                       entry.Resource5=num.intValue();
                       entry.resourceId5=rad.Resource_Allocation__c;
                  }
                   mapList.put(rad.outletID__c,entry);
               }
               
           }
            // DynamicColumnEntryList=mapList.values();
             List<DynamicColumnEntry> CloseList=new List<DynamicColumnEntry>();//关闭门店
             List<DynamicColumnEntry> NewList=new List<DynamicColumnEntry>();//新增门店
             List<DynamicColumnEntry> NormalList=new List<DynamicColumnEntry>();//正常门店
             for(DynamicColumnEntry entry:mapList.values())
             {
                 if(entry.OutletStatus=='关闭')
                     CloseList.add(entry);
                 else if(entry.OutletStatus=='新增')
                     NewList.add(entry);
                 else
                     NormalList.add(entry);
             }
             DynamicColumnEntryList.addAll(CloseList);
             DynamicColumnEntryList.addAll(NewList);
             DynamicColumnEntryList.addAll(NormalList);
             return DynamicColumnEntryList;
     }
     //加载资源分配列表,按城市汇总
     //1:条件，2：活动ID
    public List<AllocationResourceEntry> LoadResourceAllcationListByCity(String filter,string activityId)
    {
        List<AllocationResourceEntry> option=new List<AllocationResourceEntry>();
        string sql='';
        
            sql='select Resource_Allocation__r.Product_Name__r.Name ResourceName,Resource_Allocation__r.ETOrFGCode__c ResourceCode,sum(ResourceNumber__c) Total '+
                    'from CityResourceAllcation__c where  Activity_Information__c=\''+activityId+'\' ';
           
         if(filter!=NULL || filter!='')
             sql+=filter;
       
          sql+=' group by Resource_Allocation__r.Product_Name__r.Name,Resource_Allocation__r.ETOrFGCode__c order by Resource_Allocation__r.Product_Name__r.Name';
       
         List<AggregateResult> resultList=Database.query(sql);
       
        for(AggregateResult res:resultList)
        {
            
            option.add(new AllocationResourceEntry('',(String)res.get('ResourceCode'),
                                                                              (String)res.get('ResourceName'),
                                                                              Integer.valueOf(res.get('Total')),
                                                                              0,
                                                                              Integer.valueOf(res.get('Total'))));
        }
      // System.assert(false,option);
        return option;
    }
    
   //以门店为单位加载资源分配列表
     //1:条件，2：活动ID
   public List<AllocationResourceEntry> LoadResourceAllcationListByOutlet(String filter,string activityId)
    {
        List<AllocationResourceEntry> option=new List<AllocationResourceEntry>();
      
        string sql='select sum(Resource_Quantity_Number__c) resourceTotal,Resource_Allocation__r.Product_Name__r.Name,'+
                          'Resource_Allocation__r.Product_Name__r.SKU_Code__c'+ 
                          ' from Resource_Allocation_Detail__c where  ActivityId__c=\''+activityId+'\'';
                          
         if(filter!=NULL || filter!='')
             sql+=filter;
             
         sql+=' group by  Resource_Allocation__r.Product_Name__r.Name,Resource_Allocation__r.Product_Name__r.SKU_Code__c '+
                  ' order by Resource_Allocation__r.Product_Name__r.Name';
                   
        List<AggregateResult> rsList=Database.Query(sql);
         for(AggregateResult rs:rsList)
         {
              decimal total=0;
              if(rs.get('resourceTotal')!=NULL)
                  total=(decimal)rs.get('resourceTotal');
                  
              option.add(new AllocationResourceEntry('',(string)rs.get('SKU_Code__c'),(string)rs.get('Name'),
                                    total.intValue(),0,total.intValue()));
          }
        return option;
    }
   
    //要保存的实体，要删除的实体,按个保存实体
    public void SaveAdjustmentResourceForOulet(List<DynamicColumnEntry> saveDynamicColumnEntryList,List<Resource_Allocation_Detail__c> delResourceDetailList,String parId)
    {
         List<Resource_Allocation_Detail__c> radList=new List<Resource_Allocation_Detail__c>();
         Set<Id> radIdList=new Set<Id>();
              for(DynamicColumnEntry entry:saveDynamicColumnEntryList)
              {
                  radIdList.add(entry.idString);
                  if(entry.Resource1>=0)
                  {
                      Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                      rad.Participator_Detail_Outlet__c=entry.ParticipatorId;
                      rad.Resource_Allocation__c=entry.resourceId1;
                      rad.Resource_Quantity_Number__c=entry.Resource1;//保存个的数
                      rad.Resource_Number__c=entry.ResourceCaseNumber1;//保存箱的数(第一次分配下来的箱的数)
                      rad.PlaceOrderPlussage__c=((Decimal)rad.Resource_Quantity_Number__c*0.1).round();//保存可超出的百分之十的数
                      rad.Participator_Detail_Area__c=parId;
                      rad.HasUsedResourceNumber__c=entry.HasUsedResourceNumber1;
                      radList.add(rad);
                  }
                  if(entry.Resource2>=0)
                  {
                      Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                      rad.Participator_Detail_Outlet__c=entry.ParticipatorId;
                      rad.Resource_Allocation__c=entry.resourceId2;
                      rad.Resource_Quantity_Number__c=entry.Resource2;
                      rad.Resource_Number__c=entry.ResourceCaseNumber2;
                       rad.PlaceOrderPlussage__c=((Decimal)rad.Resource_Quantity_Number__c*0.1).round();//保存可超出的百分之十的数
                       rad.Participator_Detail_Area__c=parId;
                       rad.HasUsedResourceNumber__c=entry.HasUsedResourceNumber2;
                       radList.add(rad);
                  }
                   if(entry.Resource3>=0)
                  {
                      Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                      rad.Participator_Detail_Outlet__c=entry.ParticipatorId;
                      rad.Resource_Allocation__c=entry.resourceId3;
                      rad.Resource_Quantity_Number__c=entry.Resource3;
                      rad.Resource_Number__c=entry.ResourceCaseNumber3;
                       rad.PlaceOrderPlussage__c=((Decimal)rad.Resource_Quantity_Number__c*0.1).round();//保存可超出的百分之十的数
                       rad.Participator_Detail_Area__c=parId;
                       rad.HasUsedResourceNumber__c=entry.HasUsedResourceNumber3;
                       radList.add(rad);
                  }
                   if(entry.Resource4>=0)
                  {
                      Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                      rad.Participator_Detail_Outlet__c=entry.ParticipatorId;
                      rad.Resource_Allocation__c=entry.resourceId4;
                      rad.Resource_Quantity_Number__c=entry.Resource4;
                      rad.Resource_Number__c=entry.ResourceCaseNumber4;
                       rad.PlaceOrderPlussage__c=((Decimal)rad.Resource_Quantity_Number__c*0.1).round();//保存可超出的百分之十的数
                       rad.Participator_Detail_Area__c=parId;
                       rad.HasUsedResourceNumber__c=entry.HasUsedResourceNumber4;
                       radList.add(rad);
                  }
                   if(entry.Resource5>=0)
                  {
                      Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                      rad.Participator_Detail_Outlet__c=entry.ParticipatorId;
                      rad.Resource_Allocation__c=entry.resourceId5;
                      rad.Resource_Quantity_Number__c=entry.Resource5;
                      rad.Resource_Number__c=entry.ResourceCaseNumber5;
                       rad.PlaceOrderPlussage__c=((Decimal)rad.Resource_Quantity_Number__c*0.1).round();//保存可超出的百分之十的数
                       rad.Participator_Detail_Area__c=parId;
                       rad.HasUsedResourceNumber__c=entry.HasUsedResourceNumber5;
                       radList.add(rad);
                  }
                 
              }
                //先删除
                  delete delResourceDetailList;
                  insert radList;
        }
        //OT页面获取动态列
         //动态列
     public List<DynamicColumnEntry> getDynamicColumnEntryList(List<AggregateResult> rsList){
         List<DynamicColumnEntry> dceList=new List<DynamicColumnEntry>();
         Map<String,DynamicColumnEntry> mapList=new map<String,DynamicColumnEntry>();//资源列表
          for(AggregateResult rs:rsList){ 
           decimal total=(decimal)rs.get('resourceTotal');
           if(!mapList.containsKey((String)rs.get('Area__c'))){
               DynamicColumnEntry entry=new DynamicColumnEntry();
               entry.OutletName=(String)rs.get('Area__c');
               entry.Resource1=total.intValue();
               entry.resourceId1=String.valueOf(rs.get('Resource_Allocation__c')).substring(0,15);         
               entry.Resource2=-1;
               entry.Resource3=-1;
               entry.Resource4=-1;
               entry.Resource5=-1;
               mapList.put((String)rs.get('Area__c'),entry);
            }else {
                   DynamicColumnEntry entry=mapList.get((String)rs.get('Area__c'));
                   if(entry.Resource2==-1)
                   {
                      entry.Resource2=total.intValue();
                      entry.resourceId2=String.valueOf(rs.get('Resource_Allocation__c')).substring(0,15);
                    }else  if(entry.Resource3==-1){
                      entry.Resource3=total.intValue();
                      entry.resourceId3=String.valueOf(rs.get('Resource_Allocation__c')).substring(0,15);
                   }
                  else  if(entry.Resource4==-1){
                     entry.Resource4=total.intValue();
                    entry.resourceId4=String.valueOf(rs.get('Resource_Allocation__c')).substring(0,15);
                  }else if(entry.Resource5==-1){
                    entry.Resource5=total.intValue();
                    entry.resourceId5=String.valueOf(rs.get('Resource_Allocation__c')).substring(0,15);
                }
                   mapList.put((String)rs.get('Area__c'),entry);
            }
                // OutletColumnList.add(rad.Participator_Detail_Outlet__r.Outlet_Name__r.Name );
             }
             dceList=mapList.values(); 
       return dceList;
     }
     /*该方法用在SSY，KA，Region活动，KAM和SRTM保存CityResourceAllocation
     1.kaName不为NULL,regionName为NULL时是KAM调用该方法
     2.kaName为NULL,regionName不为NULL时是SRTM调用该方法
     activityType：活动类型
     typeStr：资源类型
     */
     public void SaveCityResourceAllocation(String typeStr,string activityId,string kaName,string regionName,string activityType,List<DynamicColumnEntry> DynamicColumnEntryList)
     {
         List<Resource_Allocation_Detail__c> radList=new List<Resource_Allocation_Detail__c>();
         List<Participator_Detail_Outlet__c> ParOutletList=new List<Participator_Detail_Outlet__c>();
         List<Activity_Target_And_Allocation_Total__c> cityTargetList=new List<Activity_Target_And_Allocation_Total__c>();
         String typeCity=typeStr;
         if(activityType=='SSY')
                typeCity+='City';
         //查询KA门店,和KA城市的Target
         if(kaName!=NULL)
         {         
             ParOutletList=[select Id,TargetNumber__c,KA__c,City__c,OutletResourceType__c 
                                   from Participator_Detail_Outlet__c 
                                    where Participator_Area__r.Activity_Name__c=:activityId 
                                    and KA__c=:kaName and OutletResourceType__c=:typeStr];
             cityTargetList=[select CityName__c,TargetNumber__c from Activity_Target_And_Allocation_Total__c
                                      where Activity_Information__c=:activityId and Type__c=:typeCity and KAName__c=:kaName];
         }
        if(regionName!=NULL)
         {
             ParOutletList=[select Id,TargetNumber__c,KA__c,City__c,OutletResourceType__c 
                                   from Participator_Detail_Outlet__c 
                                    where Participator_Area__r.Activity_Name__c=:activityId 
                                    and Region__c=:regionName and OutletResourceType__c=:typeStr];
             cityTargetList=[select CityName__c,TargetNumber__c from Activity_Target_And_Allocation_Total__c
                                      where Activity_Information__c=:activityId and Type__c=:typeCity and Region__c=:regionName];
         }
         //按城市保存参与者
         map<string,List<Participator_Detail_Outlet__c>> mapParticipatorList=new map<string,List<Participator_Detail_Outlet__c>>();
         for(Participator_Detail_Outlet__c pdo: ParOutletList)
         {
             if(!mapParticipatorList.containsKey(pdo.City__c))
             {
                 List<Participator_Detail_Outlet__c> parList=new List<Participator_Detail_Outlet__c>();
                 parList.add(pdo);
                 mapParticipatorList.put(pdo.City__c,parList);
             }
             else
             {
                 List<Participator_Detail_Outlet__c> parList=mapParticipatorList.get(pdo.City__c);
                 parList.add(pdo);
                 mapParticipatorList.put(pdo.City__c,parList);
             }
         }
       
         //取出城市Target
         map<string,double> mapCityTargetList=new map<string,double>();
         for(Activity_Target_And_Allocation_Total__c ataat:cityTargetList)
         {
             mapCityTargetList.put(ataat.CityName__c,ataat.TargetNumber__c);
         }
         List<CityResourceAllcation__c> cityResList=new List<CityResourceAllcation__c>();
             for(DynamicColumnEntry entry:DynamicColumnEntryList)
             {
                 List<Participator_Detail_Outlet__c> parList=mapParticipatorList.get(entry.OutletName);
                 double target=mapCityTargetList.get(entry.OutletName);
                        
                  if(entry.Resource1>=0)
                  {
                        CityResourceAllcation__c cityRes=new CityResourceAllcation__c();
                        cityRes.Activity_Information__c=activityId;
                        cityRes.Region__c=entry.Region;
                        cityRes.Subregion__c=entry.Subregion;
                        cityRes.Area__c=entry.Area;
                        cityRes.CityName__c=entry.OutletName;
                        cityRes.OutletNumber__c=parList.size();
                        if(kaName!=NULL)
                        {
                            cityRes.KAName__c=kaName;
                            cityRes.Type__c=typeCity;
                        }
                        else
                            cityRes.Type__c=typeCity;
                            
                        cityRes.Resource_Allocation__c=entry.resourceId1;
                        cityRes.ResourceNumber__c=entry.Resource1;
                        cityResList.add(cityRes);
                        
                       List<Resource_Allocation_Detail__c> resultList=CreateResourceAllocationDetail(parList,entry.resourceId1,target,entry.Resource1*entry.ResourcePackSize1);
                    
                       if(resultList!=NULL)
                            radList.addAll(resultList);
                  }
                  if(entry.Resource2>=0)
                  {
                        CityResourceAllcation__c cityRes=new CityResourceAllcation__c();
                        cityRes.Activity_Information__c=activityId;
                        cityRes.CityName__c=entry.OutletName;
                        cityRes.Region__c=entry.Region;
                        cityRes.Subregion__c=entry.Subregion;
                        cityRes.Area__c=entry.Area;
                        cityRes.OutletNumber__c=parList.size();
                        if(kaName!=NULL)
                        {
                            cityRes.KAName__c=kaName;
                            cityRes.Type__c=typeCity;
                        }
                        else
                            cityRes.Type__c=typeCity;
                        cityRes.Resource_Allocation__c=entry.resourceId2;
                        cityRes.ResourceNumber__c=entry.Resource2;
                        cityResList.add(cityRes);
                        
                        List<Resource_Allocation_Detail__c> resultList=CreateResourceAllocationDetail(parList,entry.resourceId2,target,entry.Resource2*entry.ResourcePackSize2);
                       if(resultList!=NULL)
                           radList.addAll(resultList);
                  }
                  if(entry.Resource3>=0)
                  {
                        CityResourceAllcation__c cityRes=new CityResourceAllcation__c();
                        cityRes.Activity_Information__c=activityId;
                        cityRes.CityName__c=entry.OutletName;
                        cityRes.Region__c=entry.Region;
                        cityRes.Subregion__c=entry.Subregion;
                        cityRes.Area__c=entry.Area;
                        cityRes.OutletNumber__c=parList.size();
                        if(kaName!=NULL)
                        {
                            cityRes.KAName__c=kaName;
                            cityRes.Type__c=typeCity;
                        }
                        else
                            cityRes.Type__c=typeCity;
                        cityRes.Resource_Allocation__c=entry.resourceId3;
                        cityRes.ResourceNumber__c=entry.Resource3;
                        cityResList.add(cityRes);
                        
                        List<Resource_Allocation_Detail__c> resultList=CreateResourceAllocationDetail(parList,entry.resourceId3,target,entry.Resource3*entry.ResourcePackSize3);
                       if(resultList!=NULL)
                           radList.addAll(resultList);
                  }
                  if(entry.Resource4>=0)
                  {
                        CityResourceAllcation__c cityRes=new CityResourceAllcation__c();
                        cityRes.Activity_Information__c=activityId;
                        cityRes.CityName__c=entry.OutletName;
                        cityRes.Region__c=entry.Region;
                        cityRes.Subregion__c=entry.Subregion;
                        cityRes.Area__c=entry.Area;
                        cityRes.OutletNumber__c=parList.size();
                        if(kaName!=NULL)
                        {
                            cityRes.KAName__c=kaName;
                            cityRes.Type__c=typeCity;
                        }
                        else
                            cityRes.Type__c=typeCity;
                            
                        cityRes.Resource_Allocation__c=entry.resourceId4;
                        cityRes.ResourceNumber__c=entry.Resource4;
                        cityResList.add(cityRes);
                        
                        List<Resource_Allocation_Detail__c> resultList=CreateResourceAllocationDetail(parList,entry.resourceId4,target,entry.Resource4*entry.ResourcePackSize4);
                       if(resultList!=NULL)
                           radList.addAll(resultList);
                  }
                   if(entry.Resource5>=0)
                  {
                        CityResourceAllcation__c cityRes=new CityResourceAllcation__c();
                        cityRes.Activity_Information__c=activityId;
                        cityRes.CityName__c=entry.OutletName;
                        cityRes.Region__c=entry.Region;
                        cityRes.Subregion__c=entry.Subregion;
                        cityRes.Area__c=entry.Area;
                        cityRes.OutletNumber__c=parList.size();
                        if(kaName!=NULL)
                        {
                            cityRes.KAName__c=kaName;
                            cityRes.Type__c=typeCity;
                        }
                        else
                            cityRes.Type__c=typeCity;
                            
                        cityRes.Resource_Allocation__c=entry.resourceId5;
                        cityRes.ResourceNumber__c=entry.Resource5;
                        cityResList.add(cityRes);
                        
                        List<Resource_Allocation_Detail__c> resultList=CreateResourceAllocationDetail(parList,entry.resourceId5,target,entry.Resource5*entry.ResourcePackSize5);
                       if(resultList!=NULL)
                           radList.addAll(resultList);
                  }
             }
             insert cityResList;
             //先删除现有的resource allocation details
             if(activityType=='SSY'){
             if(kaName!=NULL)
                 delete [select id from Resource_Allocation_Detail__c where ActivityId__c=:activityId and Participator_Detail_Outlet__r.KA__c=:kaName];
             if(regionName!=NULL)   
             {
                 delete [select id from Resource_Allocation_Detail__c 
                             where ActivityId__c=:activityId and Participator_Detail_Outlet__r.KA__c=NULL 
                             and Participator_Detail_Outlet__r.Region__c=:regionName
                             and ReourceOutletType__c=:typeStr];
             }  //  System.assert(false,radList);
            }else if(activityType=='KA'){
                  delete [select id from Resource_Allocation_Detail__c where ActivityId__c=:activityId and Participator_Detail_Outlet__r.KA__c=:kaName and ReourceOutletType__c=:typeStr];
            }
             insert radList;
          
     }
     //创建资源分配明细
     public List<Resource_Allocation_Detail__c> CreateResourceAllocationDetail(List<Participator_Detail_Outlet__c> parList,string resouceId,double cityTarget,Integer resourceNumber)
     {
         Integer hasResourceNumber=0;
         List<Resource_Allocation_Detail__c> radList=new  List<Resource_Allocation_Detail__c>();
         for(Participator_Detail_Outlet__c pdo:parList)
         {
             double num=0;
             if(pdo.TargetNumber__c!=0 && pdo.TargetNumber__c!=NULL && cityTarget!=0)
                 num=pdo.TargetNumber__c/cityTarget*resourceNumber;
            Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
            rad.Participator_Detail_Outlet__c=pdo.id;
            rad.Resource_Allocation__c=resouceId;
            rad.Resource_Quantity_Number__c=num.round().intValue();
            radList.add(rad);
            hasResourceNumber+=num.round().intValue();
         }
         //补齐
         if(hasResourceNumber>resourceNumber)//分多了
             return AscAjdustResource(hasResourceNumber,resourceNumber,radList);
         if(resourceNumber>hasResourceNumber)//分少了
             return DescAjdustResource(hasResourceNumber,resourceNumber,radList);
             
         return radList;
     }
        //获取用户所管的KA列表值
        public List<SelectOption> UserKAOptionList()
        {
            List<SelectOption> optionList=new List<SelectOption>();
            User u=[select Key_Account__c from User where id=:UserInfo.getUserId()];
            string kaString=u.Key_Account__c;
            for(string str:kaString.split(';'))
            {
                optionList.add(new SelectOption(str,str));
            }
     
            return optionList;
        }
        //参与KA
        public List<SelectOption> ParticipatorKAList(string activityId,Boolean hasAll)
        {
            set<string> keyString=new set<string>();
            List<SelectOption> option=new List<SelectOption>();
            if(hasAll)
                option.add(new SelectOption('0','ALL'));
            for(ParticipatorArea__c area:[select KA__c from ParticipatorArea__c where Activity_Name__c=:activityId and  KA__c!=NULL])
            {
                if(!keyString.contains(area.KA__c))
                {
                    option.add(new SelectOption(area.KA__c,area.KA__c));
                    keyString.add(area.KA__c);
                }
            }
            return option;
        }
        //参与城市
        public List<SelectOption> ParticipatorCityList(string activityId,Boolean hasAll)
        {
            set<string> keyString=new set<string>();
            List<SelectOption> option=new List<SelectOption>();
            if(hasAll)
                option.add(new SelectOption('0','ALL'));
            for(Participator_Detail_Outlet__c area:[select City__c from Participator_Detail_Outlet__c where ActivityId__c=:activityId and  City__c!=NULL])
            {
                if(!keyString.contains(area.City__c))
                {
                    option.add(new SelectOption(area.City__c,area.City__c));
                    keyString.add(area.City__c);
                }
            }
            return option;
        }
        //参与活动ASM
   /*       public List<SelectOption> ParticipatorASMList(string activityId,Boolean hasAll,List<Participator_Detail_Area__c> paList,List<KAMConfirmASMDate__c> KAMConfirmASMDateList)
        {
            // set<string> keyString=new set<string>();
            set<string> asmConfirmedList=new set<string>();//确认过的ASM列表
            List<SelectOption> option=new List<SelectOption>();
            if(hasAll)
                option.add(new SelectOption('','ALL'));
             for(KAMConfirmASMDate__c kamConfirm:KAMConfirmASMDateList) {
               asmConfirmedList.add(kamConfirm.Participator_Detail_Area__r.id);
              }
             // System.assert(false,KAMConfirmASMDateList);
             for(Participator_Detail_Area__c area:paList){
               if(!asmConfirmedList.contains(area.id))
                     option.add(new SelectOption(area.id,area.Submit_ASM__r.Name));             
              }
             return option;
        }*/
        //活动ID，1：KA，2：OT，3：KA and OT,4:ET or FG
        public void GenerateNewOutlet(string activityId,integer newType)
        {
            List<Resource_Allocation_Detail__c> resAllDetailsList=new List<Resource_Allocation_Detail__c>();
            string sql='select id,KA_Allocation_Number__c,OT_Allocation_Number__c,Resource_Allocation_Number__c '+
                              'from Resource_Allocation__c where Activity_Information_Name__c=\''+activityId+'\'';
       /*     if(newType==1)
                sql+=' and KA_Allocation_Number__c>0';
           else if(newType==2)
               sql+=' and  OT_Allocation_Number__c>0';
            else if(newType==3)
                sql+=' and KA_Allocation_Number__c>0 and  OT_Allocation_Number__c>0';
           else if(newType==4)
               sql+=' and Resource_Allocation_Number__c>0';*/
               
           List<Resource_Allocation__c> raList=Database.query(sql);     
           
           List<Participator_Detail_Outlet__c> participatorList=[select id,KA__c from Participator_Detail_Outlet__c
                                                                        where ActivityId__c=:activityId and Resource_Allcation_Count__c=0];
           for(Resource_Allocation__c resourct:raList)
           {
               for(Participator_Detail_Outlet__c par:participatorList)
               {
                   if(par.KA__c!=NULL && resourct.KA_Allocation_Number__c>0)//KA
                   {
                       Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                       rad.Participator_Detail_Outlet__c=par.Id;
                       rad.Resource_Allocation__c=resourct.id;
                       rad.Resource_Number__c=0;
                       rad.Resource_Quantity_Number__c=0;
                       resAllDetailsList.add(rad);
                   }
                   if(par.KA__c==NULL && resourct.OT_Allocation_Number__c>0)//OT
                   {
                       Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                       rad.Participator_Detail_Outlet__c=par.Id;
                       rad.Resource_Allocation__c=resourct.id;
                       rad.Resource_Number__c=0;
                       rad.Resource_Quantity_Number__c=0;
                       resAllDetailsList.add(rad);
                   }
                   if(resourct.Resource_Allocation_Number__c>0)
                   {
                       Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                       rad.Participator_Detail_Outlet__c=par.Id;
                       rad.Resource_Allocation__c=resourct.id;
                       rad.Resource_Number__c=0;
                       rad.Resource_Quantity_Number__c=0;
                       resAllDetailsList.add(rad);
                   }
               }  
           }
           if(resAllDetailsList.size()>0)
               insert resAllDetailsList;
        }
        //补齐资源分配数，资源数分配超出或少于总分配数时使用,只限于总部发起活动时使用
        //activityId(活动ID)
      /* public void PolishingAllocationResourceNumber(string activityId)
       {
            List<AggregateResult> groupResourceList;
            Map<Id,Resource_Allocation__c> mapResourceList;
             //如果是ＫＡ/OT时
             
            groupResourceList=[select sum(Resource_Number__c) SumTotal,Participator_Detail_Outlet__r.OutletResourceType__c,
                                                 Resource_Allocation__c from Resource_Allocation_Detail__c 
                                                 where ActivityId__c=:activityId and Resource_Allocation__c!=NULL
                                                  group by Participator_Detail_Outlet__r.OutletResourceType__c,Resource_Allocation__c];
                
              mapResourceList=new Map<Id,Resource_Allocation__c>([select id,Product_Name__c,OT_Allocation_Number__c, 
                                                                                                             KA_Allocation_Number__c,Resource_Allocation_Number__c  
                                                                                                              from Resource_Allocation__c
                                                                                                             where Activity_Information_Name__c=:activityId ]);
               for(AggregateResult rs:groupResourceList)
               {
                   double sumTotal=double.valueOf(rs.get('SumTotal'));//资源数
                   String resourceId=String.valueOf(rs.get('Resource_Allocation__c'));
                   string typeStr=string.valueOf(rs.get('OutletResourceType__c'));
                   if(mapResourceList.containsKey(resourceId))//找出资源
                   {
                       Resource_Allocation__c res=mapResourceList.get(resourceId);
                       if(typeStr=='KA')
                       {
                          if(res.KA_Allocation_Number__c >0 && res.KA_Allocation_Number__c != sumTotal)
                          {
                              if(res.KA_Allocation_Number__c > sumTotal)//分少了,把资源数大的门店取出分配
                              {
                               
                                 DescAdjustResource(res.KA_Allocation_Number__c,sumTotal,resourceId,typeStr);                                                       
                              }
                              else if(res.KA_Allocation_Number__c < sumTotal)//分多了,减去资源数小的门店
                              {
                                  AscAjdustResource(res.KA_Allocation_Number__c,sumTotal,resourceId,typeStr );        
                              }
                          } 
                       }
                      else if(typeStr =='OT')
                       {
                          if(res.OT_Allocation_Number__c >0 && res.OT_Allocation_Number__c != sumTotal)
                          {
                              if(res.OT_Allocation_Number__c > sumTotal)//分少了,把资源数大的门店取出分配
                              {
                                  DescAdjustResource(res.OT_Allocation_Number__c,sumTotal,resourceId,typeStr);                                                                  
                              }
                              else if(res.OT_Allocation_Number__c < sumTotal)//分多了,减去资源数小的门店
                              {
                                  AscAjdustResource(res.OT_Allocation_Number__c,sumTotal,resourceId,typeStr);        
                              }
                          } 
                       }
                       else
                       {
                            if(res.Resource_Allocation_Number__c>0 && res.Resource_Allocation_Number__c != sumTotal)
                            {
                                 if(res.Resource_Allocation_Number__c > sumTotal)//分少了,把资源数大的门店取出分配
                                 {
                                      DescAdjustResource(res.Resource_Allocation_Number__c,sumTotal,resourceId,typeStr);                                                                  
                                 }
                                  else if(res.Resource_Allocation_Number__c < sumTotal)//分多了,减去资源数小的门店
                                  {
                                      AscAjdustResource(res.Resource_Allocation_Number__c,sumTotal,resourceId,typeStr);        
                                  }
                          } 
                       }
                   }
               }
       }
       */
        //分少了,把资源数大的门店取出分配
     //总的资源数，己分配资源数
    /* public void DescAdjustResource(Decimal allocationNumber,Decimal hasBeenAllocationNumber,Id resourceId,string typeStr)
     {
          Decimal num=allocationNumber-hasBeenAllocationNumber;
         // Integer Count=num.intValue();
          List<Resource_Allocation_Detail__c>  resDetailList=[select Id,Resource_Number__c,Resource_Quantity_Number__c,
                                                                                                  Resource_Allocation__r.Product_Name__r.Pack_Size_C__c
                                                                                                  from Resource_Allocation_Detail__c 
                                                                                                  where ReourceOutletType__c=:typeStr
                                                                                                  and Resource_Allocation__c=:resourceId
                                                                                                   order by Resource_Number__c desc
                                                                                                   limit:num.intValue()];
                                                                                                  
            for(Resource_Allocation_Detail__c rad:resDetailList)
           {
                rad.Resource_Number__c=rad.Resource_Number__c+1;
                //转换成个
                rad.Resource_Quantity_Number__c=rad.Resource_Number__c*rad.Resource_Allocation__r.Product_Name__r.Pack_Size_C__c;
           }  
            update resDetailList;      
     }
      //分多了,减去资源数小的门店
     //总的资源数，己分配资源数
     public void AscAjdustResource(Decimal allocationNumber,Decimal hasBeenAllocationNumber,Id resourceId,string typeStr)
     {
          Decimal num=hasBeenAllocationNumber-allocationNumber;
          List<Resource_Allocation_Detail__c>  resDetailList=[select Id,Resource_Number__c,Resource_Quantity_Number__c,
                                                                                                  Resource_Allocation__r.Product_Name__r.Pack_Size_C__c
                                                                                                  from Resource_Allocation_Detail__c 
                                                                                                  where Participator_Detail_Outlet__r.OutletResourceType__c=:typeStr
                                                                                                  and Resource_Allocation__c=:resourceId
                                                                                                  and Resource_Number__c>0
                                                                                                  order by Resource_Number__c asc
                                                                                                  limit:num.intValue()];
            for(Resource_Allocation_Detail__c rad:resDetailList)
           {
                rad.Resource_Number__c-=1;
                //转换成箱
                rad.Resource_Quantity_Number__c=rad.Resource_Number__c*rad.Resource_Allocation__r.Product_Name__r.Pack_Size_C__c;
           }  
            update resDetailList;      
     }
     */
  
      //重载方法
     //己经分配的资源数，总的资源数,要调整的列表;分多了,减去占比少的
     public List<Resource_Allocation_Detail__c> AscAjdustResource(Integer hasBeenAssignTotalResourceNum,Integer resourceNum,List<Resource_Allocation_Detail__c> radList)
     {
          Integer decrease=hasBeenAssignTotalResourceNum-resourceNum;
          for(Resource_Allocation_Detail__c rad:radList)
          {
                 if(decrease>0)
                 {
                     if(rad.Resource_Quantity_Number__c>0)
                     {
                         rad.Resource_Quantity_Number__c-=1;
                         decrease--;
                     }
                 }
                 if(decrease==0)
                     break;
         }
         
         return radList;
     }
     //重载方法
       //己经分配的资源数，总的资源数,要调整的列表;分少了占比多的多加
     public List<Resource_Allocation_Detail__c> DescAjdustResource(Integer hasBeenAssignTotalResourceNum,Integer resourceNum,List<Resource_Allocation_Detail__c> radList)
     {
         Integer decrease=resourceNum-hasBeenAssignTotalResourceNum;
         for(Integer i=radList.size()-1;i>=0;i--)
         {
             if(decrease>0)
             {
                 radList[i].Resource_Quantity_Number__c+=1;
                 decrease--;
             }
             if(decrease==0)
                  break;
         }
         return radList;
     }
     //资源数排序并调整
     //参数：numValue=产品的规格，reourceOutletList=要调整的资源列表，hasBeenAssignTotalResourceNum=已分配的资源数，resourceNumer总的资源数
         public void getAdjustList(decimal numValue,List<Resource_Allocation_Detail__c> reourceOutletList,decimal hasBeenAssignTotalResourceNum,decimal resourceNumer){
        for(integer i=reourceOutletList.size()-1;i>0;i--){
             for(integer j=0;j<i;j++){
               if(reourceOutletList[j].Resource_Number__c>reourceOutletList[j+1].Resource_Number__c){
                    Resource_Allocation_Detail__c temp=reourceOutletList[j];
                    reourceOutletList[j]=reourceOutletList[j+1];
                    reourceOutletList[j+1]=temp;
                }
             }
         }  
        // System.debug('*******'+reourceOutletList);
         decimal decrease=hasBeenAssignTotalResourceNum-resourceNumer;
         //分多了
         if(decrease>0){
          while(decrease>0){
              for(Integer m=reourceOutletList.size()-1;m>=0;m--) {
                 if(decrease>0)  
                  {
                     if(reourceOutletList[m].Resource_Number__c>0)
                     {
                         reourceOutletList[m].Resource_Number__c-=1;
                         decrease--;
                     }
                   }
              }
            }
           }
           //分少了
           else if(decrease<0)
           {
             while(decrease<0){
                 for(Integer n=0;n<reourceOutletList.size();n++) {
                     if(decrease<0)  {
                         //if(reourceOutletList[n].Resource_Number__c>0)   {
                             reourceOutletList[n].Resource_Number__c+=1;
                              decrease++;
                       //   }
                      }
                  }
                }
           }
          for(Resource_Allocation_Detail__c rad:reourceOutletList){
              rad.Resource_Quantity_Number__c=numValue* rad.Resource_Number__c;
           }
           insert reourceOutletList;
   }
   
    //资源数排序并调整,将调整好的资源返回,按个调整
     //参数：numValue=产品的规格，reourceOutletList=要调整的资源列表，hasBeenAssignTotalResourceNum=已分配的资源数，resourceNumer总的资源数
     public void ReturnAdjustList(List<Resource_Allocation_Detail__c> reourceOutletList,decimal hasBeenAssignTotalResourceNum,decimal resourceNumer)
     {
        for(integer i=reourceOutletList.size()-1;i>0;i--)
        {
             for(integer j=0;j<i;j++)
             {
               if(reourceOutletList[j].Resource_Quantity_Number__c>reourceOutletList[j+1].Resource_Quantity_Number__c)
               {
                    Resource_Allocation_Detail__c temp=reourceOutletList[j];
                    reourceOutletList[j]=reourceOutletList[j+1];
                    reourceOutletList[j+1]=temp;
                }
             }
         }  
        // List<Resource_Allocation_Detail__c> updateList=new List<Resource_Allocation_Detail__c>();
         
         decimal decrease=hasBeenAssignTotalResourceNum-resourceNumer;
         //分多了
         if(decrease>0)
         {
              for(Integer m=0;m<reourceOutletList.size();m++) 
              {
                 if(decrease>0)  
                  {
                         if(reourceOutletList[m].Resource_Quantity_Number__c>0)
                         {
                             reourceOutletList[m].Resource_Quantity_Number__c-=1;
                            // reourceOutletList[m].Resource_Quantity_Number__c=numValue* reourceOutletList[m].Resource_Number__c;
                            // updateList.add(reourceOutletList[m]);
                             decrease--;
                         }
                   }
                   else if(decrease==0)
                   {
                       break;
                   }
              }
            //  update updateList;
           }
           else if(decrease<0)//分少了
           {
               for(Integer m=reourceOutletList.size()-1;m>=0;m--)  
               {
                   if(decrease<0)
                   {
                       if(reourceOutletList[m].Resource_Quantity_Number__c==NULL)
                           reourceOutletList[m].Resource_Quantity_Number__c=0;
                           
                       reourceOutletList[m].Resource_Quantity_Number__c+=1;
                     //  reourceOutletList[m].Resource_Quantity_Number__c=numValue* reourceOutletList[m].Resource_Number__c;
                     //  updateList.add(reourceOutletList[m]);
                       decrease++;
                   }
                    else if(decrease==0)
                   {
                       break;
                   }
               }
            //   update updateList;
           }
          insert reourceOutletList;
         //  return reourceOutletList;
   }
   //补齐资源调整,总部by city调整
   public List<CityResourceAllcation__c> ReturnCityAdjustList(List<CityResourceAllcation__c> resList,Integer hasBeenAssignTotalResourceNum,Integer totalResourceNum)
   {
       Integer num=hasBeenAssignTotalResourceNum-totalResourceNum;
       if(num>0)//分多了
       {
           for(CityResourceAllcation__c ka:resList)
           {
               if(num>0)
               {
                   if(ka.ResourceNumber__c>0)
                   {
                       ka.ResourceNumber__c-=1;
                       num--;
                   }
               }
               else
                   break;
           }
       }
       else if(num<0)
       {
           for(CityResourceAllcation__c ka:resList)
           {
               if(num<0)
               {
                   ka.ResourceNumber__c+=1;
                   num++;
               }
           }
       }
       return resList;
   }
     //根据title找出相应的用户邮箱地址
     public List<string> getUserEmailAddress(string title,string activityId)
     {
         List<string> addressList=new List<string>();
         if(title=='NTMKT')//总部
         {
            Activity_Information__c info= [select OwnerId from Activity_Information__c where id=:activityId];
            for(User u:[select Email from User where id=:info.OwnerId])
                addressList.add(u.Email);
         }
         if(title=='KAM')
         {
             string filter='';
             for(ParticipatorArea__c area:[select KA__c from ParticipatorArea__c where Activity_Name__c=:activityId ])
             {
                 if(filter!='')
                         filter+=' or ';
                         
                 filter+=' Key_Account__c includes(\''+area.KA__c+'\')';
             }
             for(User u:database.query('select Email from User where Title_Functional__c=\'KAM\' and ('+filter+')'))
                 addressList.add(u.Email);
         
         }
         if(title=='SRTM')
         {
             Set<string> regionList=new Set<string>();
             for(ParticipatorArea__c area:[select Region__c from ParticipatorArea__c where Activity_Name__c=:activityId])
                    regionList.add(area.Region__c);
             for(User u:[select Email from User where UserRegion__c in: regionList and Title_Functional__c='SRTM'])
                 addressList.add(u.Email);
         }
           return addressList;
     }
     //reset Resource
   public void ResetALLData(List<ActivityResourceEntry> ResourceEntryList){
      for(ActivityResourceEntry r:ResourceEntryList){
            // r.Res.KA_Allocation_Number__c=0;
          //   r.Res.OT_Allocation_Number__c=0;
             r.Res.Resource_Allocation_Number__c=0;
         }
   }
   //DeleteResource
   public void DelResource(List<ActivityResourceEntry> ResourceEntryList){
          for(Integer i=0;i<ResourceEntryList.size();i++)
        {
            ActivityResourceEntry activityRes=ResourceEntryList[i];
            if(activityRes.isCheck)
            {
                if(activityRes.Res.id!=null)
                        delete activityRes.Res;
                ResourceEntryList.remove(i);
                i--;
            }
        }
   }
   //Add Resource
    public void AddResources(String ResourceType,List<ActivityResourceEntry> ResourceEntryList,Resource_Allocation__c ResourceObject){
         boolean flag=true;
         if(ResourceEntryList.size()>=5)
             throw new CustomException ('资源数目不能大于5！');
             // flag=false;
         for(ActivityResourceEntry entry:ResourceEntryList)
          {
              if( entry.res.Product_Name__c==ResourceObject.Product_Name__c)
                  throw new CustomException ('该资源已被选择！');
                   // flag=false;
                  //  break;
           }
          if(flag){
             //查找产品Code
           Product2 pro=[select SKU_Code__c from Product2 where id=:ResourceObject.Product_Name__c limit 1];
           ResourceObject.ETOrFGCode__c=pro.SKU_Code__c;   
           ResourceObject.Resource_Allocation_Number__c=0;
           ResourceObject.Resource_Type__c=ResourceType;
           ResourceEntryList.add(new ActivityResourceEntry(false,ResourceObject));
          // integer i=ResourceEntryList.size()-1;
           //ResourceEntryList[i].Res.Resource_Allocation_Number__c=0;
         //  ResourceEntryList[i].Res.Resource_Type__c=ResourceType;
          } 
   }
   //获取 ASM邮件地址 ,用于SRTM发送邮件给ASM,根据SRTM的子区来查询ASM
       public List<String> getToAddress(String RecordId)
       {
             List<String> ToAddress=new List<String>();
             Set<string> areaList=new Set<string>();
             set<string> subregion=new set<string>();
             set<string> rsmIdList=new set<string>();
             //找出所有的Area
             for(CityResourceAllcation__c city:[select Area__c,SubRegion__c from CityResourceAllcation__c where Activity_Information__c=:RecordId and Type__c!='KA'])
             {   
                  areaList.add(city.Area__c);
                  subregion.add(city.SubRegion__c);
             }
            //找出所有直接汇报给RSM ID
            for(User u:[select id from User where Title__c='Regional Sales Manager' and UserSubRegion__c in:subregion])
                rsmIdList.add(u.id);
                
          //找出所有的ASM ID 
          for(User u:[select id,Email from User where Title__c='Area/District Sales Manager' and UserAreaValue__c in:areaList and ManagerId in:rsmIdList])
             ToAddress.add(u.Email);
             
             return ToAddress;  
    }   
    //按片区找出所有的ASM ID
   public List<User> getASMList(string subregion)
   {
       //找出所有直接汇报给RSM ID
       set<string> rsmIdList=new set<string>();
       map<string,User> userList=new map<string,User>();
        for(User u:[select id from User where Title__c='Regional Sales Manager' and UserSubRegion__c =:subregion])
            rsmIdList.add(u.id);
        //找出所有的ASM ID 
       for(User u:[select id,Name,Email from User where Title__c='Area/District Sales Manager' and UserSubRegion__c=:subregion and ManagerId in:rsmIdList])
           userList.put(u.id,u);   
            
            return userList.values();
   }
    //获得用户所在的区域
     public String getUserRegion(){
       User user=[select Id,UserRegion__c,Title_Functional__c,Name,Title__c from User where Id=:UserInfo.getUserId()];//ASM/DSM 
       String region=user.UserRegion__c;
       return region;
    }
    public User getUserInfo()
    {
        User user=[select Id,UserRegion__c,UserSubRegion__c,UserAreaValue__c,Title_Functional__c,Name,Title__c from User where Id=:UserInfo.getUserId()];
        return user;
    }
    
    //城市区域销售占比计算 
    //region：当前用户所在的大区
    //RecordId:活动ID
    //activityType:活动类型
    public List<DynamicColumnEntry> getPercentSaleOrRecourceForCity(String activityType,String region,String RecordId)
    {
        List<CityResourceAllcation__c> cityResList=new List<CityResourceAllcation__c>();
        List<Activity_Target_And_Allocation_Total__c> ataatList=new List<Activity_Target_And_Allocation_Total__c>();
        if(activityType=='SSY'){
          cityResList=[select CityName__c,ResourceNumber__c from CityResourceAllcation__c
                                                                             where Activity_Information__c=:RecordId 
                                                                             and Type__c='OTCity' and  Region__c=:region];
        
          ataatList=[select CityName__c,TargetNumber__c 
                                                                                                from Activity_Target_And_Allocation_Total__c 
                                                                                                where Activity_Information__c=:RecordId 
                                                                                                and Type__c='OTCity' and Region__c=:region];
        }else{
           cityResList=[select CityName__c,ResourceNumber__c from CityResourceAllcation__c
                                                                             where Activity_Information__c=:RecordId 
                                                                             and  Region__c=:region];
        
          ataatList=[select CityName__c,TargetNumber__c 
                                                                                                from Activity_Target_And_Allocation_Total__c 
                                                                                                where Activity_Information__c=:RecordId 
                                                                                                and Region__c=:region];
        }
        map<string,double> CityResourceMapList=new  map<string,double>();      
        double ResourceTotal=0;                                                                            
        for(CityResourceAllcation__c cityRes:cityResList)
        {
            if(CityResourceMapList.containsKey(cityRes.CityName__c))
            {
                double num=CityResourceMapList.get(cityRes.CityName__c)+cityRes.ResourceNumber__c;
                CityResourceMapList.put(cityRes.CityName__c,num);
            }
            else
            {
                CityResourceMapList.put(cityRes.CityName__c,cityRes.ResourceNumber__c);
            }
            ResourceTotal+=cityRes.ResourceNumber__c;
        }
        
        map<string,Integer> CityTargetMapList=new map<string,Integer>();
       Integer TotalTarget=0;
        for(Activity_Target_And_Allocation_Total__c ataat:ataatList)
        {
            TotalTarget+=Integer.valueOf(ataat.TargetNumber__c);
        }
        
        List<DynamicColumnEntry> TotalPercentList = new List<DynamicColumnEntry>();
        
          map<string,double > TotalCityTargetMapList=new map<string,double >();
         for(Activity_Target_And_Allocation_Total__c ataat:ataatList)
        {
          if(!TotalCityTargetMapList.containsKey(ataat.CityName__c)){
            TotalCityTargetMapList.put(ataat.CityName__c,ataat.TargetNumber__c);
          }else{
             decimal num=TotalCityTargetMapList.get(ataat.CityName__c)+ataat.TargetNumber__c;
             TotalCityTargetMapList.put(ataat.CityName__c,num);
          }
        }
        for(String keyStr:TotalCityTargetMapList.keySet())
        {
            decimal target=TotalCityTargetMapList.get(keyStr)/TotalTarget*100; 
            decimal resNum=CityResourceMapList.get(keyStr)/ResourceTotal*100;
            //system.assert(false,CityResourceMapList.get(ataat.CityName__c));
            DynamicColumnEntry entry=new DynamicColumnEntry();
             entry.OutletName=keyStr;
             entry.resourceId1=String.valueOf(target.round())+'%';
             entry.resourceId2=String.valueOf(resNum.round())+'%';
             TotalPercentList.add(entry);
        }
        
  /*      
        for(Activity_Target_And_Allocation_Total__c ataat:ataatList)
        {
            double target=ataat.TargetNumber__c/TotalTarget*100;
            double resNum=CityResourceMapList.get(ataat.CityName__c)/ResourceTotal*100;
            //system.assert(false,CityResourceMapList.get(ataat.CityName__c));
            DynamicColumnEntry entry=new DynamicColumnEntry();
             entry.OutletName=ataat.CityName__c;
             entry.resourceId1=String.valueOf(target.round())+'%';
             entry.resourceId2=String.valueOf(resNum.round())+'%';
             TotalPercentList.add(entry);
        }  */
        return TotalPercentList;
       
    }
    //获取所有下级TSR的门店的城市，只限于ASM身份调用
    //activityId：活动ID；userList:下级用户ID
    public map<string,List<SelectOption>> getSubordinateCity(string activityId,List<Id> userList)
    {
        map<string,List<SelectOption>> cityAndKAList=new map<string,List<SelectOption>>();
        set<string> onlyCityList=new set<string>();
        set<string> onlyKAList=new set<string>();
        List<SelectOption> cityList=new List<SelectOption>();
        List<SelectOption> kaList=new List<SelectOption>();
        for(Participator_Detail_Outlet__c pdo:[select City__c,KA__c from Participator_Detail_Outlet__c where ActivityId__c=:activityId and OwnerId in:userList])
        {
            if(!onlyCityList.contains(pdo.City__c))
            {
                if(pdo.City__c!=NULL)
                {
                    cityList.add(new SelectOption(pdo.City__c,pdo.City__c));
                    onlyCityList.add(pdo.City__c);
                }
            }
            if(pdo.KA__c!=NULL)
            {
                if(!onlyKAList.contains(pdo.KA__c))
                {
                    onlyKAList.add(pdo.KA__c);
                    kaList.add(new SelectOption(pdo.KA__c,pdo.KA__c));
                }
            }
        }
        if(cityList.size()>0)
            cityAndKAList.put('City',cityList);
        if(kaList.size()>0)
            cityAndKAList.put('KA',kaList);
            
        return cityAndKAList;
    }
   
    //赋值并获取分配数值
    public map<String,Integer> getResourceAllDetailByFile(map<id,Resource_Allocation_Detail__c> resourceDetailList,string[] rowString,integer i,map<String,Integer> totNumMap,String key){
           if(rowString[i]!=NULL && rowString[i]!='') {
                 if(Integer.valueOf(rowString[i+2])<0)
                      throw new CustomException ('资源分配数值不能小于0');
                 Integer num=0;
                 Resource_Allocation_Detail__c rad=(Resource_Allocation_Detail__c)resourceDetailList.get(rowString[i]);
                 num=Integer.valueOf(rowString[i+2]);
                 rad.Resource_Quantity_Number__c=num;
                 resourceDetailList.put(rad.id,rad);
                 //String key=rad.Participator_Detail_Outlet__r.KA__c+rad.Participator_Detail_Outlet__r.OutletResourceType__c+rad.ProductName__c;   //标识
                 if(totNumMap.containsKey(key))             
                     num+=totNumMap.get(key)+num;
                 totNumMap.put(key,num);
              }
                 return totNumMap;
    }
    public void getActivityBrandDetailByFile(map<id,Activity_Competition_Brand_Detail__c> CompetitionList,string[] rowString,integer i){
            if(rowString[i]!=NULL && rowString[i]!='')//Competition 1
              {
                 if(Decimal.valueOf(rowString[i+6])<0)
                      throw new CustomException ('金额分配数值不能小于0');
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[i]);
                  acbd.Start_Date__c=Date.valueOf(rowString[i+4]);
                  acbd.End_Date__c=Date.valueOf(rowString[i+5]);
                  acbd.Money__c=Decimal.valueOf(rowString[i+6]);
                  acbd.Display_Type__c=rowString[i+7];
                  CompetitionList.put(acbd.id,acbd);
              }
    }
     //获取上传文件内容并赋值，针对SSY和Region活动
    public void getFileContent(map<id,Activity_Competition_Brand_Detail__c> CompetitionList,map<id,Resource_Allocation_Detail__c> resourceDetailList,string[] contentList,String typeStr,Set<String> keySet,map<String,Integer> AllPretotNumList){
         map<String,Integer> totNummap=new map<String,Integer>(); //ET1分配总数
        //   System.assert(false,CompetitionList); 
    

           for(integer i=1;i<contentList.size();i++){
              string[] rowString=contentList[i].split(',');
            //  string[] rowString=b64Decrypted.split(',');
              String key=rowString[1]+rowString[2]+rowString[3];   //标识
              getResourceAllDetailByFile(resourceDetailList,rowString,4,totNummap,key); //ET1
              getResourceAllDetailByFile(resourceDetailList,rowString,7,totNummap,key); //ET2
              getResourceAllDetailByFile(resourceDetailList,rowString,10,totNummap,key); //ET3
              getResourceAllDetailByFile(resourceDetailList,rowString,13,totNummap,key); //ET4
              getResourceAllDetailByFile(resourceDetailList,rowString,16,totNummap,key); //ET5
              
              getActivityBrandDetailByFile(CompetitionList,rowString,34);  //Competition 1
              getActivityBrandDetailByFile(CompetitionList,rowString,42);  //Competition 2
              getActivityBrandDetailByFile(CompetitionList,rowString,50);  //Competition 3
              getActivityBrandDetailByFile(CompetitionList,rowString,58);  //Competition 4
              getActivityBrandDetailByFile(CompetitionList,rowString,66);  //Competition 5
              getActivityBrandDetailByFile(CompetitionList,rowString,74);  //Competition 6
              getActivityBrandDetailByFile(CompetitionList,rowString,82);  //Competition 7
              getActivityBrandDetailByFile(CompetitionList,rowString,90);  //Competition 8
              if(typeStr=='KA'){
                getResourceAllDetailByFile(resourceDetailList,rowString,19,totNummap,key); //FG1
                getResourceAllDetailByFile(resourceDetailList,rowString,22,totNummap,key); //FG1
                getResourceAllDetailByFile(resourceDetailList,rowString,25,totNummap,key); //FG1
                getResourceAllDetailByFile(resourceDetailList,rowString,28,totNummap,key); //FG1
                getResourceAllDetailByFile(resourceDetailList,rowString,31,totNummap,key); //FG1
                }
          }
          //判断用户分配总数与数据库中总数是否一致，不一致则不能上传文件  
         for(String key:keySet){
             if(totNummap.containsKey(key)) {
                if(totNummap.get(key)!=AllPretotNumList.get(key))
                     throw new CustomException ('分配总数与实际存在总数不相等，请重新分配');
             }
         }
  update resourceDetailList.values();
         update CompetitionList.values();
        System.assert(false,CompetitionList);
    }
   
  public List<String> getEmail(List<ParticipatorArea__c> paList){
   //public List getEmialAddress(){
        List<string> addressList=new List<string>();
        string filter='';
        for(ParticipatorArea__c area:paList)
        {
         if(filter!='')
            filter+=' or ';            
         filter+=' Key_Account__c includes(\''+area.KA__c+'\')';
        }
            // for(User u:database.query('select Email from User where Title_Functional__c=\'KAM\' and ('+filter+')')){
             //    addressList.add(u.Email);
             //  }
       for(User u:database.query('select Email from User where Title_Functional__c=\'KAM\' and ('+filter+')'))
          addressList.add(u.Email);
       return addressList;
    } 
     //ASM提交
   public void SendEmailToASM(Activity_Information__c ActivityInfo,Set<String> sList){
     
                    
                          List<String> emailList=new List<String>();
                          List<String> allEmail=getASMEmailAddress(ActivityInfo.id,sList);
                          List<Participator_Detail_Area__c> pdaList=new List<Participator_Detail_Area__c>();
                       
                          pdaList=[select Area__c,Submit_ASM__r.Email,Approve_Description__c from Participator_Detail_Area__c where Activity_Information__c=:ActivityInfo.id and IsActive__c=true and Approve_Description__c!='拒绝'];
                           for(Participator_Detail_Area__c pda:pdaList){
                              boolean flag=true;
                              for(String email:allEmail){
                                 if(email==pda.Submit_ASM__r.Email && pda.Approve_Description__c!='拒绝'){
                                    flag=false;
                                    break;
                                 }
                               }
                                 if(flag)
                                   emailList.add(pda.Submit_ASM__r.Email);                
                           } 
                         
                          //System.assert(false,allEmail);               
                          String BodyString='【'+ActivityInfo.Name+'】活动距离提交时间即将结束,请尽快登陆凤凰系统进行提交,谢谢！';
                          String subject='确认【'+ActivityInfo.Name+'】活动时间';
                          if(pdaList!=NULL && pdaList.size()>0)
                            EmailHander.SendMail(BodyString,emailList,subject,'',null);
                          else
                            EmailHander.SendMail(BodyString,allEmail,subject,'',null);
                   
   }
   
   
    //获取 ASM邮件地址 ,用于SSY，Region活动邮件通知ASM完成资源提交,根据SRTM是否已提交来查询ASM邮件地址
       public List<String> getASMEmailAddress(String RecordId,Set<String> sList){
                List<User> uList=[select Email,UserRegion__c,UserAreaValue__c from User where Title__c='Area/District Sales Manager'and UserAreaValue__c=:sList];
                List<String> ToAddress=new List<String>();
                for(integer i=0;i<uList.size();i++){
                    User u=uList[i];
                     for(String s:sList){
                          if(u.UserAreaValue__c.contains(s)){
                             ToAddress.add(u.Email);
                             break;
                          }
                       }
                  }
             return ToAddress;  
    }   
    
   //添加参与者
      public void AddParticipators(String flag,Map<String,ActivityParticipatorEntry> mapParticipatorAreaList,List<ActivityParticipatorEntry> ParticipatorAreaList,CommonAttribute PlaceAttribute,boolean IsNc,Activity_Information__c ActivityInit)
      {   
         List<Participator_Detail_Outlet__c> outletDetail=new List<Participator_Detail_Outlet__c>();
         set<Id> AllParticipatorOutletId=new set<Id>();
       
         String sqlParticipator='select Outlet_Name__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=\''+ActivityInit.id+'\' and OutletResourceType__c=\''+flag+'\' and Region__c=\''+PlaceAttribute.RegionSelectedValue+'\'';
          //查出已存在的门店
           for(Participator_Detail_Outlet__c par:database.query(sqlParticipator))
           {
                AllParticipatorOutletId.add(par.Outlet_Name__c);
            }
        //查出所有符合条件的outlet,按KA放入map中
         Map<String,Set<Id>> accountMap=new Map<String,Set<Id>>();
        Map<String,Set<Account >> accountsMap=new Map<String,Set<Account >>();
         String sql='select id,OwnerId,OutletRegion__c,OutletSubRegion__c,OutletArea__c, Chain_Customer__c,Outlet_Type__c,Channel__c from Account where Active_Status__c=\'正常营业\'' +Filter(flag,ActivityInit,PlaceAttribute.RegionSelectedValue,PlaceAttribute.SubRegionSelectedValue,PlaceAttribute.AreaSelectedValue,PlaceAttribute.KASelectedValue,PlaceAttribute.OutletTypeSelectedValue,PlaceAttribute.ChannelSelectedValue,IsNc);
         set<Id> ListCountLastActual=new  set<Id>();
         set<Account > ListCount=new  set<Account >();
     
         for(Account a:Database.Query(sql)){
           ListCountLastActual.add(a.id);
           ListCount.add(a);
         }
         
         //对于KA和SSY的KA
        if((ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL) || (ActivityInit.Activity_Type__c=='SSY' && PlaceAttribute.KASelectedValue==NULL && flag=='KA' )){
          for(Account a:ListCount)
         { //  System.assert(false,sql);
           if(a.Chain_Customer__c!='' && a.Chain_Customer__c!=NULL){
               if(!accountMap.containsKey(a.Chain_Customer__c))
               {
                  Set<Id>  accList=new Set<Id>(); 
                  Set<Account >  accSet=new Set<Account >(); 
                    accList.add(a.id);
                    accSet.add(a);
                  accountMap.put(a.Chain_Customer__c,accList);
                  accountsMap.put(a.Chain_Customer__c,accSet);
                 
                }
             else
             {  
                   Set<Id> accList=accountMap.get(a.Chain_Customer__c);
                    Set<Account >  accSet=accountsMap.get(a.Chain_Customer__c);
                   accList.add(a.id);
                   accSet.add(a);
                   accountMap.put(a.Chain_Customer__c,accList);
                   accountsMap.put(a.Chain_Customer__c,accSet);
              }
           }
         }
     }else{
       accountMap.put('kanotnull',ListCountLastActual);
     }
        //PA
    
       List<ParticipatorArea__c> paList=new List<ParticipatorArea__c>();
         //Set<String> areaList=new List<String>();
       String subRegion='';
       String area='';
      if(PlaceAttribute.SubRegionSelectedValue!='0')
           subRegion=PlaceAttribute.SubRegionSelectedValue;
       if(PlaceAttribute.AreaSelectedValue!='0')
           area=PlaceAttribute.AreaSelectedValue;
         //查出所有Area
       String key=PlaceAttribute.RegionSelectedValue+subRegion+area+PlaceAttribute.KASelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;  
       
      for(String keyStr: accountMap.keySet()){
         Set<Id> accoutList=new Set<Id>();
         String ka=PlaceAttribute.KASelectedValue;
         if((ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL) || (ActivityInit.Activity_Type__c=='SSY' && PlaceAttribute.KASelectedValue==NULL && flag=='KA' )){
           ka=keyStr;  
           accoutList=accountMap.get(keyStr);
           key=PlaceAttribute.RegionSelectedValue+subRegion+area+keyStr+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;  
          
           }
         else{
           accoutList=ListCountLastActual;
         }
         integer countPar=0;
         if(accoutList.containsAll(AllParticipatorOutletId) || AllParticipatorOutletId.containsAll(accoutList)){
           
          if(accoutList.size()-AllParticipatorOutletId.size()>0)
              countPar=accoutList.size()-AllParticipatorOutletId.size();              
         }else{
             countPar=accoutList.size();
         } 
             
           if(!mapParticipatorAreaList.containsKey(key)){
               ParticipatorArea__c par=new ParticipatorArea__c(Activity_Name__c=ActivityInit.id,
                                                                                  Region__c=PlaceAttribute.RegionSelectedValue,
                                                                                  Sub_region__c=subRegion,
                                                                                  Area__c=area,
                                                                                  OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                                  Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                                 KA__c=ka,
                                                                                 Type__c=flag,
                                                                                   IsNCOrNot__c=IsNc,
                                                                                 Outlet_Sum_Total__c=countPar
                                                                                 ); 
              //parMap.put(key,par); 
              if(countPar>0) 
                 paList.add(par);                                                                   
              ActivityParticipatorEntry entry=new ActivityParticipatorEntry (false,par);                                            
              mapParticipatorAreaList.put(key,entry);      
          //   System.assert(false, key); 
              //System.assert(false, mapParticipatorAreaList);
              if(mapParticipatorAreaList.size()>0)
               {
                     ParticipatorAreaList.clear();
                    for(ActivityParticipatorEntry  ee:mapParticipatorAreaList.values())
                     {
                          ParticipatorAreaList.add(new ActivityParticipatorEntry(false,ee.ParArea));
                     }  
                }                                                                   
               
              //  areaList.add(p);
         // System.assert(false,parMap);
       }
     }
        insert paList;
       
       for(ParticipatorArea__c pa:paList){
          //outletDetail.clear();
         
          Set<Account> accountSet=new Set<Account>();
         if((ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL) || (ActivityInit.Activity_Type__c=='SSY' && PlaceAttribute.KASelectedValue==NULL && flag=='KA' )){
            accountSet =accountsMap.get(pa.KA__C);
         }else{
           accountSet=ListCount;
         } 
       
          if(accountSet!=NULL){
          for(Account acc:accountSet){
            if(!AllParticipatorOutletId.contains(acc.Id)){
           
                     outletDetail.add(new Participator_Detail_Outlet__c(Outlet_Name__c=acc.id,
                                                                        Participator_Area__c=pa.Id,
                                                                        Outlet_Type__c='正常营业',
                                                                        OutletResourceType__c=flag,
                                                                        OwnerId=acc.OwnerId));
                  
              AllParticipatorOutletId.add(acc.Id);                                                                                      
               }
            } 
            }
             
               //  insert  outletDetail;     
          }
        //  System.assert(false,outletDetail);  
          insert  outletDetail;     
              
         PlaceAttribute.RegionSelectedValue='';
         PlaceAttribute.SubRegionSelectedValue='';
         PlaceAttribute.AreaSelectedValue='';
         PlaceAttribute.OutletTypeSelectedValue='';
         PlaceAttribute.ChannelSelectedValue='';
          PlaceAttribute.KASelectedValue='';             
        
          }  
      public String Filter(String flag,Activity_Information__c ActivityInit,String region,String SubRegion,String area,String KA,String outletType,String channel,boolean IsNc)
      {//System.assert(false,SubRegion);
            String filter='';
           if(region!='' && region!=NULL && region!='0')
          {
                            filter+=' and ';
                            filter+='OutletRegion__c=\''+region+'\'';
           }
          if(SubRegion!='' && SubRegion!=NULL && SubRegion!='0')
          {
                            filter+=' and ';
                            filter+='OutletSubRegion__c=\''+SubRegion+'\'';
           }
           if(area!='' && area!=NULL && area!='0')
          {
                            filter+=' and ';
                            filter+='OutletArea__c=\''+area+'\'';
           }
           if(KA!='' && KA!=NULL && KA!='0')
          {
                            filter+=' and ';
                            filter+='Chain_Customer__c=\''+KA+'\'';
           }
           else
           {
               if(ActivityInit.Activity_Type__c=='SSY' && flag=='OT'){
                   filter+=' and ';
                    filter+='Chain_Customer__c=NULL';
                    }
           }
          if(outletType!='' && outletType!=NULL && outletType!='0')
          {
                            filter+=' and ';
                            filter+='Outlet_Type__c=\''+outletType+'\'';
           }
             if(channel!='' && channel!=NULL && channel!='0')
              {
                              filter+=' and ';
                             filter+='Channel__c=\''+channel+'\'';
              }
             if(IsNc==true)//是否是NC店
                  filter+=' and With_NC_or_not__c ='+IsNc;
                  
             filter+=' and (Outlet_Type__c=\'全国重点客户\' or Outlet_Type__c=\'区域重点客户\' or Outlet_Type__c=\'婴儿用品店\' or Outlet_Type__c=\'目录直送店\' or Outlet_Type__c=\'其他\')';
             filter+=' and Chain_Customer__c !=\'经销商 \'';
              return filter;
      }  
      
      //刷新最新的从非NC转NC的门店
      ////参数
      //activityId:活动ID
      //activityStartDate:活动开始时间
      //activityType:活动类型
      //hasOT：是否要添加OT类型的门店,hasKA:是否要添加KA类型的门店,hasRegion:是否要添加Region类型的门店
    public void RefreshOutlet(string activityId,Date activityStartDate,string activityType,Boolean hasOT,Boolean hasKA,Boolean hasRegion)
    {
        if(hasOT || hasKA || hasRegion)
        {
              //取得当前用户所在的Area
               string area=getUserInfo().UserAreaValue__c;
               List<string> areaList=area.split(';');
               string areaFilterStr='';
               for(string str:areaList)
               {
                   if(areaFilterStr!='')
                       areaFilterStr+=' or ';
                   areaFilterStr+=' Area_SMS__c=\''+str+'\'';
               }
              map<string,Participator_Detail_Outlet__c> ParticipatorOutletList=new  map<string,Participator_Detail_Outlet__c>();
               set<Id> outletIdList=new set<Id>();    
               set<string> regionOutletIdList=new set<string>();
              for(Participator_Detail_Outlet__c par: [select Outlet_Name__c,Area__c,Channel__c,KA__c,OutletResourceType__c,
                                                                       Participator_Area__c,Region__c,SubRegion__c,OutletType__c
                                                                       from Participator_Detail_Outlet__c 
                                                                        where Area__c in: areaList and ActivityId__c=:activityId])
              {
                  outletIdList.add(par.Outlet_Name__c);//添加SSY活动的门店
                  regionOutletIdList.add(par.Outlet_Name__c+par.OutletResourceType__c);//添加SSY活动的门店
              }
              
               map<string,Participator_Detail_Outlet__c> insertMapList=new map<string,Participator_Detail_Outlet__c>();
               //查找由非NC转成NC的门店，时间为活动开始前四周，范围为当前用户所在的区域
               List<SynchronizeLog__c> synchList=new List<SynchronizeLog__c>();
               DateTime SDate=activityStartDate.addMonths(-1);//活动开始前四周
               string dateString=SDate.format('yyyy-MM-dd')+'T00:00:00.000Z';
               
                String sql='select OutletId__c,KA_SMS__c,Outle_Type_SMS__c,Channel_SMS__c,  Area_SMS__c,Region_SMS__c,'+
                                    '  SubRegion_SMS__c  from SynchronizeLog__c where WITH_NC_OR_NOT__c=true and CreatedDate<='+dateString+
                                    ' and DataType__c=\'SMS\' and ('+areaFilterStr+')';      
                                       
               if(activityType=='SSY')
               {   
                  if(hasOT && !hasKA)//只有OT
                      sql+=' and KA_SMS__c=NULL';
                  if(!hasOT && hasKA)//只有KA
                      sql+=' and KA_SMS__c!=NULL';
               }
                 synchList=Database.query(sql);
                 for(ParticipatorArea__c par:[select id,Area__c,Channel__c, KA__c,OutletType__c,Region__c,Sub_region__c,Activity_Name__c,Type__c
                                                           from ParticipatorArea__c where Activity_Name__c=:activityId])
                 {
                      for( SynchronizeLog__c synch:synchList)
                       {
                            string ssyKey=String.valueOf(synch.OutletId__c)+String.valueOf(par.Activity_Name__c);
                            string regionKey=String.valueOf(synch.OutletId__c)+String.valueOf(par.Activity_Name__c)+par.Type__c;
                            Participator_Detail_Outlet__c parNew=new Participator_Detail_Outlet__c();
                            parNew.Participator_Area__c=par.id;
                            parNew.Outlet_Type__c='正常营业';
                            parNew.Outlet_Name__c=synch.OutletId__c;
                            parNew.OutletResourceType__c=par.Type__c;
                            parNew.TargetNumber__c=0;
                            if(activityType=='SSY')
                            {
                                if(!outletIdList.contains(synch.OutletId__c))
                                {
                                       if(par.KA__c!=NULL && synch.KA_SMS__c==par.KA__c)//KA门店
                                       {
                                           CheckOutletPlace(insertMapList,ssyKey,parNew,par,synch);
                                       }
                                       if(synch.KA_SMS__c==NULL && par.KA__c==NULL)//OT门店
                                           CheckOutletPlace(insertMapList,ssyKey,parNew,par,synch);
                                }
                            }
                            if(activityType=='Region')
                            {
                                 if(!regionOutletIdList.contains(par.Type__c+synch.OutletId__c))
                                 {
                                     CheckOutletPlace(insertMapList,regionKey,parNew,par,synch);
                                        if(insertMapList.containsKey(regionKey))//比较KA
                                       {
                                           if(par.KA__c!=NULL && par.KA__c!=synch.KA_SMS__c)
                                               insertMapList.remove(regionKey);
                                       }
                                 }
                            }
                      }
                 }
            
            insert insertMapList.values();
            CreateResourceAllocationDetailsForNewOutlet(activityType,activityId);
         }
     }
     //根据参与者的条件添加符合条件的门店
    public void CheckOutletPlace(map<String,Participator_Detail_Outlet__c> insertList,string key,Participator_Detail_Outlet__c pdo,ParticipatorArea__c par,SynchronizeLog__c acc)
    {
        if(acc.Region_SMS__c==par.Region__c)//判断大区是否相等
        {
              if(par.Sub_region__c!=NULL)
              {
                  if(par.Sub_region__c==acc.SubRegion_SMS__c)//判断片区是否相等
                  {
                      if(par.Area__c!=NULL)
                      {
                          if(par.Area__c==acc.Area_SMS__c)
                              insertList.put(key,pdo);
                      }
                      else
                          insertList.put(key,pdo);
                  }
               }
               else
                   insertList.put(key,pdo);
          }
          if(insertList.containsKey(key))//比较渠道和门店类型
          {
              if(par.OutletType__c!=NULL && par.OutletType__c!=acc.Outle_Type_SMS__c)
                  insertList.remove(key);
              if(par.Channel__c!=NULL && par.Channel__c!=acc.Channel_SMS__c)    
                  insertList.remove(key);
          }
    }
    //创建资源分配信息,为新增的门店和非NC转NC的门店
    public void CreateResourceAllocationDetailsForNewOutlet(string activityType,string activityId)
    {
        //找出所有的没有Resource Allocation Details,分配资源
            List<Resource_Allocation_Detail__c> InsertRadList=new  List<Resource_Allocation_Detail__c>();
            List<Participator_Detail_Outlet__c> queryParticipatorOutletList=new List<Participator_Detail_Outlet__c>();
            queryParticipatorOutletList=[select id,OutletResourceType__c,KA__c  from Participator_Detail_Outlet__c 
                                                where Resource_Allcation_Count__c=0 and ActivityId__c=:activityId ];
                                                
            List<Resource_Allocation__c> resourceList=new List<Resource_Allocation__c>();
            string resourceSqlStr='select id,Resource_Type__c,KA_Allocation_Number__c,OT_Allocation_Number__c '+
                                                 ' from Resource_Allocation__c '+
                                                 'where Activity_Information_Name__c=\''+activityId+'\'';
                                                          
            if(activityType=='SSY')
                resourceSqlStr+=' and (KA_Allocation_Number__c>0 or OT_Allocation_Number__c>0)';
          resourceList=Database.query(resourceSqlStr);
       
            for(Resource_Allocation__c ra:resourceList)
            {
                for(Participator_Detail_Outlet__c par:queryParticipatorOutletList)
                {
                    if(activityType=='SSY')
                   {
                        if(par.KA__c==NULL && ra.OT_Allocation_Number__c>0)//OT
                        {
                             Resource_Allocation_Detail__c rad=new  Resource_Allocation_Detail__c();
                             rad.Participator_Detail_Outlet__c=par.Id;
                             rad.Resource_Allocation__c=ra.Id;
                             rad.Resource_Quantity_Number__c=0;
                             InsertRadList.add(rad);
                        }
                        else if(par.KA__c!=NULL && ra.KA_Allocation_Number__c>0)
                        {
                            Resource_Allocation_Detail__c rad=new  Resource_Allocation_Detail__c();
                            rad.Participator_Detail_Outlet__c=par.Id;
                            rad.Resource_Allocation__c=ra.Id;
                            rad.Resource_Quantity_Number__c=0;
                            InsertRadList.add(rad);
                        }
                    }
                    else
                    {
                        if(ra.Resource_Type__c==par.OutletResourceType__c)
                        {
                            Resource_Allocation_Detail__c rad=new  Resource_Allocation_Detail__c();
                            rad.Participator_Detail_Outlet__c=par.Id;
                            rad.Resource_Allocation__c=ra.Id;
                            rad.Resource_Quantity_Number__c=0;
                            InsertRadList.add(rad);
                        }
                    }
                }
            }
        
          insert  InsertRadList;
    }
    //检查ASM是否可以提交，只有直接汇报给RSM的ASM才可以提交
    public Boolean CheckSubmit()
    {
        boolean isOK=false;
        User currentManagerUser=[select ManagerId from User where id=:UserInfo.getUserId()];//查出ManagerId
        User mUser=[select Title__c from User where Id=:currentManagerUser.ManagerId];
        if(mUser.Title__c=='Regional Sales Manager')
            isOK=true;
            
         return isOK;
    }
}